/**
 * @(#)PursuitClassLoader.java
 *
 *
 * @author Duyun Chen
 * @version 1.00 2008/10/7
 */
package Pursuit_Client;

import java.io.*;

public class PursuitClassLoader extends ClassLoader 
{
	private PursuitPlayer player = null;
	private Class<Object> activeClass = null;
	
	@SuppressWarnings("unchecked")
	public PursuitClassLoader(File classFile) 
	{ 
    	byte[] classRawBytes = null;
    	
		try 
		{	//read in raw byte data from a file
    		classRawBytes = new byte[(int)classFile.length()];
			FileInputStream fileInputStream = new FileInputStream(classFile);
			fileInputStream.read(classRawBytes);
		}
		catch (FileNotFoundException e) 
		{	PursuitClient.print("Error: File Not Found.");	}
		catch (IOException e1) 
		{	PursuitClient.print("Error: File IOException");	}

    	try 
    	{	//create a class from byte[] by the magical function defineClass
    		Class<Object> defineClass = (Class<Object>) defineClass(removeClassExtension(classFile.getName()), classRawBytes, 0, classRawBytes.length);
			activeClass = defineClass;
    	}
    	catch (ClassFormatError cfe) 
    	{
			PursuitClient.print("Error: Wrong Class Format! -> " + classFile.getName() + ". EPIC FAIL!");
			return;
    	}
    	catch (NoClassDefFoundError ncdfe) 
    	{
    		PursuitClient.print("Error: Bad Class Definition. Make sure the class implements pursuit_client.PursuitPlayer");
    		return;
    	}
    	
    	if (activeClass != null) 
    	{	
	    	try 
	    	{	//neat method that indirectly creates an instance from the loaded class
	    		player = (PursuitPlayer)activeClass.newInstance();
	    	}
	    	catch (Exception e) 
	    	{	PursuitClient.print(e.getMessage());	}
    	}
    	else 
    		PursuitClient.print("Error: Failed to create Class from file");
    }
    
	//truncates the .class part of a filename
    private String removeClassExtension(String in) 
    {
    	int index = in.lastIndexOf(".class");
    	return index == -1? in:in.substring(0, index);
    }
    
    public PursuitPlayer getPlayer() 
    { 	return player;   }
    
    public Class<Object> getPlayerClass() 
    { 	return activeClass;  }
}